########################################################################
#  Pyfm - personal finance data-base
#  Copyright (C) 2007,8 Ehud Ben-Reuven
#  udi@benreuven.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#########################################################################
"""Interface to the historical quote module.

getFX() - retrieve foreign exchange rates

"""

from quote import quote
from lib import conf
from obj.dt import DT

def getpre(dt,last,offline):
    if offline==None:
        offline = 'T' != conf.get('ONLINE')[0]
        
    t = dt.dt.timetuple()
    dtstr = '%4d%02d%02d' % (t[0], t[1], t[2])
    fromdtstr = dtstr
    if last:
        fromdtstr = quote.beforeFirst(fromdtstr)
    return (dtstr,fromdtstr,offline)

def getpost(dtstr,fx,last,fromdtstr):
    if not (dtstr in fx and fx[dtstr]):
        if last:
            for d in quote.drange(dtstr, fromdtstr):
                if d in fx and fx[d]:
                    dtstr = d
                    break
    if not (dtstr in fx and fx[dtstr]):
        raise Exception('no rate for the specified date')
    return (fx[dtstr],dtstr)

def getQuote(dt, secid, last=True, offline=None):
    scale=1
    (dtstr,fromdtstr,offline) = getpre(dt,last,offline)
    if secid.startswith('TASE=') or secid.startswith('ISIN=IL'):
        fx = quote.get('tase:'+secid[5:], fromdtstr, dtstr, offline)
        scale=1/100.
    elif secid.startswith('TICKER='):
        fx = quote.get('yahoo:'+secid[7:], fromdtstr, dtstr, offline)
    elif secid.endswith('=X') and len(secid)==8:
        return getFX(dt,secid[:3],secid[3:6],last,offline)
    elif secid.startswith('X=') and len(secid)==8:
        return getFX(dt,secid[2:5],secid[5:8],last,offline)
    else:
        raise Exception('Unknown security ID')
    s,t=getpost(dtstr,fx,last,fromdtstr)
    return float(s['close'].replace(',',''))*scale,DT(t)

def getFX(dt, fromcur, tocur, last=True, offline=None):
    if fromcur==tocur: return 1.,dt
    if not dt: return None,None
    (dtstr,fromdtstr,offline) = getpre(dt,last,offline)
    swap = False
    #if fromcur.upper() == 'ILS':
        #tmp = fromcur
        #fromcur = tocur
        #tocur = tmp
        #swap = True
    symbol = fromcur+tocur+'=X'
    if tocur=='ILS':
        try:
            fx = quote.get('boi:'+symbol, fromdtstr, dtstr, offline)
        except:
            fx = quote.get('oanda:'+symbol, fromdtstr, dtstr, offline)
    else:
        fx = quote.get('oanda:'+symbol, fromdtstr, dtstr, offline)
    s,t = getpost(dtstr,fx,last,fromdtstr)
    fx = float(s['rate'])
    if swap:
        fx = 1.0 / fx
    return fx,DT(t)

def getFXrate(dt,fromcur,tocur):
    x,d=getFX(dt,fromcur,tocur)
    return x

if __name__ == '__main__':
    print getFX(DT('20070103010101'), 'USD', 'ILS')
    print getFX(DT('20070103010101'), 'ILS', 'USD')
    print getFX(DT('20070103010101'), 'EUR', 'USD')
    print getFX(DT('20070103010101'), 'EUR', 'USD')
    print getFX(DT('20070101010101'), 'USD', 'ILS')
    try:
        print getFX(DT('20070101010101'), 'USD', 'ILS', 
                       last=False)
    except Exception, inst:
        print inst
    try:
        print getFX(DT('20170101010101'), 'USD', 'ILS', 
                       last=False, offline=True)
    except Exception, inst:
        print inst

